<template>
	<view>
		<view style="text-align: center">
			<image style="width: 530rpx;height: 530rpx;" v-if="src" :src="src" />
		</view>

		<u-gap />

		<view style="padding: 10px">
			<u-button type="success" @click="saveLocal">保存到本地</u-button>
		</view>

	</view>
</template>

<script>
export default {
	data() {
		return {
			id:'',
            src:'',
			base64:'',
		};
	},
	onLoad(e) {
		this.id = e.id
		this.createQr(this.id)
	},
	methods: {
		createQr(id){
			uni.showLoading({title:'正在生成二维码...'})
			uniCloud.callFunction({
				name:'create_qr',
				data:{
					path:'pages/edit/edit',
					id,
				}
			}).then(res=>{
				const base64 = Buffer.from(res.result.buffer).toString('base64');
				this.base64 = base64
				this.src =  `data:image/jpg;base64,${base64}`;
                uni.hideLoading()
			}).catch(e=>{
				uni.showModal({title:'错误提示', content:e})
				uni.hideLoading()
			})
        },
		saveLocal(){
			if (!this.base64) {
				return
			}
			uni.showLoading({title:'正在保存二维码...'})
			var imgSrc =  this.base64;//base64编码
			var save = uni.getFileSystemManager();
			const url = wx.env.USER_DATA_PATH+"/" + new Date().getTime() + ".png";  // url为时间戳命名方式
			console.log(url)
			save.writeFile({
				filePath: url,
				data: imgSrc,
				encoding: 'base64',
				success: res => {
					uni.saveImageToPhotosAlbum({
						filePath: url,
						success: function() {
							uni.showToast({
								title: '保存成功',
								icon: 'none'
							})
							uni.hideLoading()
						},
						fail:(e)=>{
							uni.showModal({title:'错误', content:e.errMsg})
							uni.hideLoading()
						}
					});
				}, fail: err => {
					console.error(err)
					uni.showToast({
						title: '图片保存失败',
						icon: 'none'
					})
					uni.hideLoading()
				}
			})

		}
	}
};
</script>